<template>

  <div>
    <div class="card" style="margin-bottom: 10px;">
      <el-input v-model="data.productName" :prefix-icon="Search" style="width: 300px; margin-right: 10px"
                placeholder="请输入菜品名字"></el-input>
      <el-button type="primary" style="margin-left: 10px;" @click="load">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div class="card">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="handlerAdd">新增</el-button>
      </div>
      <div style="margin-bottom: 10px;">
        <el-table :data="data.tableData">
          <el-table-column label="菜品ID" v-if="false" prop="productId" width="70"></el-table-column>
          <el-table-column label="图片">
            <template #default="scope">
              <el-image v-if="scope.row.productIcon" :src="scope.row.productIcon" :preview-src-list="[scope.row.productIcon]" style="width: 40px;height: 40px;border-radius: 4px;"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="菜品名称" prop="productName"></el-table-column>
          <el-table-column label="单价" prop="productPrice"></el-table-column>
          <el-table-column label="库存" prop="productStock"></el-table-column>
          <el-table-column label="描述" prop="productDescription"></el-table-column>
          <el-table-column label="商品状态" prop="productStatus">
            <template #default="scope">
              <el-tag v-if="scope.row.productStatus == 0" type="warning" effect="dark">正常</el-tag>
              <el-tag v-if="scope.row.productStatus == 1" type="success" effect="dark">下架</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="类目名称" prop="categoryName"></el-table-column>
          <el-table-column label="创建时间" prop="createTime"></el-table-column>
          <el-table-column label="修改时间" prop="updateTime"></el-table-column>
          <el-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDel(scope.row.productId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="card">
        <el-pagination background layout="prev, pager,next" @current-change="handelCurrentChange"
                       v-model:current-page="data.pageNum" v-model:page-size="data.pageSize" :total="data.total"/>
      </div>
    </div>
  </div>

  <el-dialog width="35%" v-model="data.formVisible" title="菜品信息" destory-on-close>
    <el-form :model="data.form" ref="formRef" :rules="rules" label-width="100px" label-position="right" style="padding-right: 40px">
      <el-form-item label="菜品名称">
        <el-input v-model="data.form.productName" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="单价">
        <el-input v-model="data.form.productPrice" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="菜品图片">
        <img :src="data.form.productIcon||'http://t0v2ajufi.hd-bkt.clouddn.com/noimg.jpg'" alt="" style="width: 40px; height: 30px;border-radius: 10%;">
        &nbsp; &nbsp;
        <el-upload action="http://localhost:8888/files/upload" list-type="picture" :on-success="handleImgUploadSuccess">
          <el-button type="primary">上传图片</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="库存">
        <el-input v-model="data.form.productStock" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="data.form.productDescription" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="商品状态">
        <el-radio-group v-model="data.form.productStatus">
          <el-radio label="0">正常</el-radio>
          <el-radio label="1">下架</el-radio>
        </el-radio-group>
      </el-form-item>
        <el-form-item label="类目名称">
          <el-select style="width: 100%" v-model="data.form.categoryType">
            <!-- 动态渲染选项 -->
            <el-option
                v-for="category in data.categoryList"
                :key="category.categoryId"
                :value="category.categoryId"
                :label="category.categoryName"
            ></el-option>
          </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
    </template>
  </el-dialog>

</template>


<script setup>
import {reactive, ref} from "vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

const data = reactive({
  productName: '',
  tableData: [],
  pageNum: 1, //当前页码
  pageSize: 5, //每页个数
  total: 0,
  formVisible: false //新增框不显示
})
// 新增：获取类目列表数据
const loadCategoryList = () => {
  request.get("/seller/ProductCategory/list")  // 假设后台有这个接口
      .then(res => {
        if (res.code === '200') {
          data.categoryList = res.data || [];
          console.log("下拉框数据:" + JSON.stringify(data.categoryList));
        } else {
          ElMessage.error("获取类目列表失败：" + res.msg);
        }
      })
      .catch(err => {
        ElMessage.error("获取类目列表出错：" + err.message);
      });
}
const formRef = ref()
loadCategoryList();
const rules = reactive({
  productName: [
    {required: true, message: '请输入菜品名字', trigger: 'blur'}
  ],
  productPrice: [
    {required: true, message: '请输入菜品单价', trigger: 'blur'}
  ]
})

//请求数据
const load = () => {
  request.get("/seller/productInfo/selectPage", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      productName: data.productName
    }
  }).then(res => {
    console.log("分页数据:" + JSON.stringify(res));
    data.tableData = res.data?.list || [];
    data.total = res.data?.total || 0;
  })
}

//翻页
const handelCurrentChange = (pageNum) => {
  // 当翻页的时候重新加载数据即可
  load()
}

//重置
const reset = () => {
  data.productNameme = ''
  load()
}

// 调用方法获取后台数据
load();

//点击新增
const handlerAdd = () => {
  data.form = {"productStatus":"0"}
  data.formVisible = true;
}


// 保存数据到后台
const save = () => {
  request.request({
    url: data.form.productId ? '/seller/productInfo/update' : '/seller/productInfo/save',
    method: data.form.productId ? 'PUT' : 'POST',
    data: data.form
  }).then(res => {
    if (res.code === '200') {
      load()    // 重新获取数据
      data.formVisible = false  // 关闭弹窗
      ElMessage.success("操作成功")
    } else {
      ElMessage.error(res.msg)
    }
  })
}

//点击编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
}

//删除
const handleDel = (productId) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/seller/productInfo/delete/' + productId).then(res => {
      if (res.code === '200') {
        load()    // 重新获取数据
        ElMessage.success("操作成功");
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(res => {
  })
}

//图片删除成功之后的回调函数
const handleImgUploadSuccess = (res) => {
  data.form.productIcon = res.data
}

</script>